<?php

declare (strict_types=1);

namespace app\common\service\bangdou;

use app\api\model\Order as OrderModel;
use app\api\model\recharge\OrderPlan as OrderPlanModel;
use app\api\model\recharge\Order as RechargeOrderModel;
use app\api\model\user\BalanceLog as BalanceLogModel;
use app\api\model\UserOauth as UserOauthModel;
use app\api\service\order\PaySuccess as OrderPaySuccesService;
use app\api\service\Payment as PaymentService;
use app\common\enum\order\PayType as OrderPayTypeEnum;
use app\common\enum\OrderType as OrderTypeEnum;
use app\common\enum\user\balanceLog\Scene as SceneEnum;
use app\common\library\helper;
use app\common\model\OrderSub as OrderSubModel;
use app\common\model\OrderGoods as OrderGoodsModel;
use app\common\model\UserOauth;
use app\common\model\OrderCallbackLog as OrderCallbackLogModel;
use app\common\service\bangdou\BdMember as BdMemberService;
use app\common\service\XinLian\OpenApi as OpenApiService;
use app\store\model\Goods as GoodsModel;

/**
 * @time:2024/01/16 17:38
 * @Author:wuqicheng
 */
class BdPay extends Common
{
    /**
     * 用户在邦豆生活级别
     * @param null $type
     * @return array|string[]|\string[][]
     */
    public static function userBdGrade($type = null)
    {
        $rabate = [/*'1' => ['id' => '1', 'name' => '普通会员', 'rabate_bd' => '0', 'rabate_coupon' => '0', 'rabate_gift_coupon' => '0'],*/
                   '2' => ['id' => '2', 'name' => '黄金会员', 'rabate_bd' => '0.1', 'rabate_coupon' => '0.1', 'rabate_gift_coupon' => '0.1'],
                   '3' => ['id' => '3', 'name' => '铂金会员', 'rabate_bd' => '0.2', 'rabate_coupon' => '0.2', 'rabate_gift_coupon' => '0.2'],
                   '4' => ['id' => '4', 'name' => '钻石会员', 'rabate_bd' => '0.3', 'rabate_coupon' => '0.3', 'rabate_gift_coupon' => '0.3']];
        if ($type) {
            if (isset($rabate[$type])) {
                return $rabate[$type];
            } else {
                return [];
            }
        } else {
            return $rabate;
        }
    }

    /**
     * 订单支付调用邦豆生活接口
     * @param $pay_data
     * @param $user_id
     * @return mixed
     * @throws \cores\exception\BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function bangddouPay($pay_data, $user_id)
    {
        if (empty($user_id)) {
            throwError('用户不存在');
        }

        //用户余额支付
        if($pay_data['bdType'] == OrderPayTypeEnum::BALANCE){
            return self::balancePayment($pay_data,$user_id);
        }
        $user = UserOauthModel::getOauth($user_id, getPlatform());

        if (!isset($user['bd_uid']) || empty($user['bd_uid'])) {
            throwError('用户bd_uid不存在');
        } else {
            $bd_uid = $user['bd_uid'];
        }
        $res_data['good_type'] = $pay_data['good_type']??'';
        $res_data['order_id'] = $pay_data['order_id'];

        $token_array = self::createToken($bd_uid);
        $type        = [7, 6, 5];
        if (in_array($pay_data['bdType'], $type)) {
            $payType = $pay_data['bdType'];
        } else {
            $payType = 1;
        }
        if ($pay_data['pay_money'] == '0.00') {//微信支付金额为0.00
            $payData = array(['payType' => $payType, 'payMoney' => $pay_data['dk_money']]);
        } else {
            if ($pay_data['dk_money'] != '0.00' && in_array($pay_data['bdType'], $type)) {
                $payData = array(['payType' => $payType, 'payMoney' => $pay_data['dk_money']],
                    ['payType' => '1', 'payMoney' => $pay_data['pay_money']]);
            } else {
                $payData = array(['payType' => '1', 'payMoney' => $pay_data['pay_money']]);
            }
        }
        $params['platform']  = 'shopping';
        $params['orderNo']   = $pay_data['order_no'];
        $params['payData']   = $payData;
        $params['openId']    = $user['oauth_id'];
        $params['timestamp'] = time();
        $sign                = self::getBangDouApiSign($params);
        $params['sign']      = $sign;
        $url                 = app()->config->get('app.bd_api_url') . '/Order/Order/pay';
        $headers             = [
            'Content-Type: application/json',
            "Authorization: Bearer {$token_array['token']}"
        ];
        $result              = helper::httpRequest($url, json_encode($params), $headers);
        $log_file            = runtime_root_path() . 'api/log/give_pay_code_' . date('y-m-d') . '.log';
        file_put_contents($log_file, print_r($result, true) . "\n", FILE_APPEND);
        $res = json_decode($result, true);
        if ($res['state'] && $res['data']['thirdPartyPayment'] == false) {
            // 获取订单详情
            $service                    = new OrderPaySuccesService($pay_data['order_no']);
            $res_data['transaction_id'] = $res['data']['data'];
            //三券支付成功处理订单信息
            $status = $service->onPaySuccess(OrderPayTypeEnum::WECHAT, $res_data);
            if (!$status) {
                throwError($service->getError());
            }
            if (isset($pay_data['good_type']) && $pay_data['good_type'] == 'virtual_good') {//虚拟商品支付
                $pay_data['user_id'] = $user_id;
                if (!self::OrderXinLianPayment($pay_data)) {
                    $orderModel = new OrderModel();
                    $orderModel->OrderCancelByOrderId($pay_data['order_id']);
                    throwError('充值失败，请联系客服！');
                }

            }
            $res['data'] = null;
        }
        return $res;
    }

    /**
     * 余额支付
     * @param $pay_data
     * @param $user_id
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \cores\exception\BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function balancePayment ($pay_data,$user_id){
        if($pay_data['pay_money'] == '0.00'){//现金部分支付金额为0
            $service                    = new OrderPaySuccesService($pay_data['order_no']);
            //余额支付成功处理订单信息
            $status = $service->onPaySuccess(OrderPayTypeEnum::BALANCE, $pay_data);
            if (!$status) {
                throwError($service->getError());
            }
            if (isset($pay_data['good_type']) && $pay_data['good_type'] == 'virtual_good') {//虚拟商品支付
                $pay_data['user_id'] = $user_id;
                if (!self::OrderXinLianPayment($pay_data)) {
                    $orderModel = new OrderModel();
                    $orderModel->OrderCancelByOrderId($pay_data['order_id']);
                    throwError('充值失败，请联系客服！');
                }

            }
            $res['state'] = $status;
            $res['data'] = null;
        }else{
            $order_no = $pay_data['order_no'].'_'.rand(1,10000);//微信支付临时订单号
            // 构建微信支付请求
            $payment = PaymentService::wechat(
                $pay_data['order_id'],
                $order_no,
                $pay_data['pay_money'],
                OrderTypeEnum::ORDER
            );
            $res['state'] = true;
            $res['errorcode'] = 0;
            $res['data']['thirdPartyPayment']= true;
            $res['data']['data'] = $payment;
        }
        return $res;
    }

    //批量订单确认收货送邦豆
    public static function saveGiveBd($orderList)
    {
        foreach ($orderList as $order) {
            $order_sub = OrderSubModel::getOrderSubBy($order['order_parent_id']);
            if (empty($order_sub)) {
                continue;
            }
            $is_rebate = true;
            if ($order_sub['deduction_value'] > 0) {//如果商品使用了邦豆与微信组合支付将不返豆
                $is_rebate = false;
            }
            $user_grade = 1;//用户在邦豆生活会员等级
            if ($order['user_id']) {
                $bd_uid   = 0;
                $userInfo = UserOauth::getOauth($order['user_id'], 'MP-WEIXIN');
                if (isset($userInfo['bd_uid']) && !empty($userInfo['bd_uid'])) {
                    $bd_uid = $userInfo['bd_uid'];
                }
                $bd_user    = BdMemberService::getUserProperty($bd_uid);//获取用户等级
                $user_grade = isset($bd_user['memberType']) ? $bd_user['memberType'] : 1;
            }
            $rebate['give_bd']          = '0.00';//该订单返邦豆
            $rebate['give_coupon']      = '0.00';//该订单返现金券
            $rebate['give_gift_coupon'] = '0.00';//该订单返礼金券
            //循环订单商品
            foreach ($order['goods'] as $goods) {
                if (
                    !empty($goods['refund'])
                    && $goods['refund']['type'] == 10      // 售后类型：退货退款
                    && $goods['refund']['audit_status'] == 10  // 商家审核：已同意
                ) {
                    continue;//退货退款订单不出返豆
                } else if ($is_rebate || $goods['is_bd'] == 2) {//订单纯现金支付或者商品不支持三券支付就返豆
                    //计算商品赠送多少邦豆
                    $rebate_data                    = self::goodsRebateBdNumber($user_grade, $goods['total_pay_price'], $goods['rebate_type']);
                    $rebateData['give_bd']          = $rebate_data['give_bd'];
                    $rebateData['give_coupon']      = $rebate_data['give_coupon'];
                    $rebateData['give_gift_coupon'] = $rebate_data['give_gift_coupon'];
                    $model                          = new OrderGoodsModel();
                    //记录每个商品返豆数量
                    $model->where('order_goods_id', $goods['order_goods_id'])->update($rebateData);
                    $rebate['give_bd']          = bcadd($rebate['give_bd'], $rebate_data['give_bd'], 2);
                    $rebate['give_coupon']      = bcadd($rebate['give_coupon'], $rebate_data['give_coupon'], 2);
                    $rebate['give_gift_coupon'] = bcadd($rebate['give_gift_coupon'], $rebate_data['give_gift_coupon'], 2);
                } else {
                    continue;//退货退款订单不出返豆
                }
            }
            //赠送三券为空
            if($rebate['give_bd']=='0.00' && $rebate['give_coupon'] == '0.00' && $rebate['give_gift_coupon'] == '0.00'){
                return true;
            }

            $token_array                       = self::createTokenByuserId($order['user_id']);
            $pay_data['timestamp']             = time();
            $pay_data['platform']              = 'shopping';
            $pay_data['rewardBangdouTotal']    = $rebate['give_bd'];
            $pay_data['rewardCouponTotal']     = $rebate['give_coupon'];
            $pay_data['rewardCouponGiftTotal'] = $rebate['give_gift_coupon'];
            $pay_data['orderNo']               = $order['order_no'];
            $pay_data['storeId']               = $order['store_id'];
            $pay_data['organId']               = self::ORGANID;
            $sign                              = self::getBangDouApiSign($pay_data);
            $pay_data['sign']                  = $sign;
            $headers                           = [
                'Content-Type: application/json',
                "Authorization: Bearer {$token_array['token']}"
            ];

            $api_url  = app()->config->get('app.bd_api_url') . '/Order/Order/sendBangdouAndCoupon';
            $result   = helper::httpRequest($api_url, json_encode($pay_data), $headers);
            $res      = json_decode($result, true);
            $log_file = runtime_root_path() . 'api/log/give_user_bd_' . date('y-m-d') . '.log';
            file_put_contents($log_file, print_r($res, true) . "\n", FILE_APPEND);
            if ($res['state'] == true) {
                $data['give_bd']          = bcadd($rebate['give_bd'], $order_sub['give_bd'], 2);//赠送的邦豆
                $data['give_coupon']      = bcadd($rebate['give_coupon'], $order_sub['give_coupon'], 2);//赠送的现金券
                $data['give_gift_coupon'] = bcadd($rebate['give_gift_coupon'], $order_sub['give_gift_coupon'], 2);//赠送的礼金券
                $data['give_bdtime']      = time();
                $data['state']            = 30;
                OrderSubModel::updateOrderSubBy($order['order_parent_id'], $data);
                $bd_type = ['7' => $rebate['give_bd'], '6' => $rebate['give_coupon'], '5' => $rebate['give_gift_coupon']];
                //新增余额变动记录
                foreach ($bd_type as $key => $value) {
                    BalanceLogModel::add(SceneEnum::ORDERGIVE, [
                        'user_id'         => (int)$order['user_id'],
                        'money'           => 0.00,
                        'correlation_id'  => $order['order_id'],
                        'bd_type'         => $key,
                        'deduction_value' => $value,
                        'store_id' => $order['store_id'],
                    ], ['order_no' => $order['order_no']]);
                }
            }
        }
        return true;
    }


    /**
     * 计算订单商品返豆数量
     * @param $user_grade 用户等级
     * @param $total_pay_price 订单总金额
     * @param $rebate_type 返豆类型
     */
    public static function goodsRebateBdNumber($user_grade, $total_pay_price, $rebate_type)
    {
        $user_grade               = self::userBdGrade($user_grade);
        $rebate_info              = GoodsModel::goodsRebateType($rebate_type);
        $data['give_bd']          = '0.00';
        $data['give_coupon']      = '0.00';
        $data['give_gift_coupon'] = '0.00';
        if (isset($user_grade['rabate_bd']) && isset($rebate_info['rabate_bd'])) {
            $data['grade_bd'] = bcmul($total_pay_price, $user_grade['rabate_bd'], 2);//会员等级赠送邦豆
            $data['good_bd']  = bcmul($total_pay_price, $rebate_info['rabate_bd'], 2);//商品类型赠送邦豆

            $data['grade_coupon'] = bcmul($total_pay_price, $user_grade['rabate_coupon'], 2);//会员等级赠送现金券
            $data['good_coupon']  = bcmul($total_pay_price, $rebate_info['rabate_coupon'], 2);//商品类型赠送现金券

            $data['grade_gift_coupon'] = bcmul($total_pay_price, $user_grade['rabate_gift_coupon'], 2);//会员等级赠送礼金券
            $data['good_gift_coupon']  = bcmul($total_pay_price, $rebate_info['rabate_gift_coupon'], 2);//商品类型赠送礼金券

            $data['give_bd']          = bcadd($data['grade_bd'], $data['good_bd'], 2);//合计赠送邦豆
            $data['give_coupon']      = bcadd($data['grade_coupon'], $data['good_coupon'], 2);//合计赠送现金券
            $data['give_gift_coupon'] = bcadd($data['grade_gift_coupon'], $data['good_gift_coupon'], 2);//合计赠送礼金券

        }
        return $data;
    }


    /**
     * @param $orderId
     * @param $transaction_id 微信订单号
     * @return false|mixed
     * 订单全额退款
     */
    /*public static function bangddouRefund($orderId,$transaction_id){
        $order = OrderSubModel::getOrderSubBy($orderId);
        if(empty($order)){
            return false;
        }
        $token_array = self::createTokenByuserId($order['user_id']);
        if($order['pay_money']>0 && $order['deduction_value']>0){
            $params['payData'] = [['payType'=>1,'payMoney'=>$order['pay_money']],
                                  ['payType'=> $order['bd_type'],'payMoney'=>$order['deduction_value']]];
        }else{
            if($order['payMoney']>0){
                $params['payData'] = [['payType'=>1,'payMoney'=>$order['pay_money']]];
            }
            if($order['deductionValue']>0){
                $params['payData'] = [['payType'=>$order['bd_type'],'payMoney'=>$order['deduction_value']]];
            }
        }
        $params['organId'] = self::ORGANID;
        $params['storeId'] = $order['store_id'];
        $params['orderId'] = $order['order_id'];
        $params['orderNo'] = $order['order_no'];
        $params['outTardeNo'] = $transaction_id;
        $params['platform'] = 'shopping';
        $params['timestamp'] = time();
        $sign = self::getBangDouApiSign($params);
        $params['sign'] = $sign;
        $url = app()->config->get('app.bd_api_url').'/Order/Order/refund';
        $headers = [
            'Content-Type: application/json',
            "Authorization: Bearer {$token_array['token']}"
        ];
        $result = httpRequest($url, json_encode($params), $headers);
        $res = json_decode($result, true);
        log_record($result);
        if($res['state'] == true){
            $data['state'] = 40;
            return OrderSubModel::updateOrderSubBy($orderId,$data);
        }
        return false;
    }*/
    /**
     * @param $orderId
     * @param $money 退款金额
     * @param $transaction_id 微信订单号
     * @return false|mixed
     * 订单取消
     */
    public static function bangdouRefund($orderInfo, $transaction_id, $money)
    {
        if (isset($orderInfo['order_parent_id'])) {
            $suborder = OrderSubModel::getOrderSubBy($orderInfo['order_parent_id']);
        }
        if (empty($suborder)) {
            throwError('订单不存在');
            return false;
        }
        /*if ($suborder['state'] != 20) {
            throwError('订单已完成请联系技术');
            return false;
        }*/
        if (is_null($money)) {
            $money = $orderInfo['pay_price'];
        }

        $payMoney = bcadd($suborder['pay_money'], $suborder['deduction_value'], 2);
        if ($money > $payMoney) {//退款金额大于支付金额
            throwError('退款金额大于支付金额');
            return false;
        }
        $ordermoney = helper::bcadd($orderInfo['pay_cash'], $orderInfo['deduction_value']);
        if ($ordermoney < $money) {
            throwError('退款金额有误');
            return false;
        }

        $cash           = '0.00';//退现金
        $deductionValue = '0.00';//退三券
        if ($orderInfo['pay_cash'] >= $money && $orderInfo['deduction_value'] == 0.00) { //纯微信支付的
            $params['payData'] = [['payType' => 1, 'payMoney' => $money]];
            $cash              = $money;
        } elseif ($orderInfo['pay_cash'] == 0.00 && $orderInfo['deduction_value'] >= $money) { //三券支付的
            $params['payData'] = [['payType' => $orderInfo['bd_type'], 'payMoney' => $money]];
            $deductionValue    = $money;
        } elseif ($orderInfo['pay_cash'] > 0.00 && $orderInfo['deduction_value'] > 0.00) {
            if ($money == $ordermoney) {
                $cash           = $orderInfo['pay_cash'];//退现金
                $deductionValue = $orderInfo['deduction_value'];//退三券
            } else {
                //三券和现金组合支付,目前商品都是支持三券的，直接按比例退，如果有商品不支持三券的，需要抛开现金商品
                $order_total_price = helper::bcadd($orderInfo['pay_cash'], $orderInfo['deduction_value']);//订单支付总金额
                $deductionValue    = helper::bcmul(helper::bcdiv($money, $order_total_price, 10), $orderInfo['deduction_value'], 2);
                $cash              = helper::bcsub($money, $deductionValue);
            }
            $params['payData'] = [['payType' => 1, 'payMoney' => $cash],
                ['payType' => $orderInfo['bd_type'], 'payMoney' => $deductionValue]];
        } else {
            throwError('退款订单不合法');
            return false;
        }


        $params['organId']       = self::ORGANID;
        $params['storeId']       = $suborder['store_id'];
        $params['orderId']       = $suborder['order_id'];
        $params['orderNo']       = $suborder['order_no'];
        $params['weixinMoney']   = $suborder['pay_original_money'];
        $params['outTardeNo']    = $transaction_id;
        $params['tmpOutTardeNo'] = $suborder['tmp_out_tarde_no'] ?? '';
        $params['platform']      = 'shopping';
        $params['timestamp']     = time();

        $sign           = self::getBangDouApiSign($params);
        $params['sign'] = $sign;
        $url            = app()->config->get('app.bd_api_url') . '/Order/Order/refund';
        $token_array    = self::createTokenByuserId($suborder['user_id']);
        $headers        = [
            'Content-Type: application/json',
            "Authorization: Bearer {$token_array['token']}"
        ];
        $result         = helper::httpRequest($url, json_encode($params), $headers);
        $res            = json_decode($result, true);
        $log_file       = runtime_root_path() . 'api/log/bd_wx_Refund_' . date('y-m-d') . '.log';
        file_put_contents($log_file, print_r($res, true) . "\n", FILE_APPEND);
        if ($res['state'] == true) {
            $data['pay_money']       = bcsub($suborder['pay_money'], $cash, 2);
            $data['deduction_value'] = bcsub($suborder['deduction_value'], $deductionValue, 2);
            OrderSubModel::updateOrderSubBy($suborder['order_id'], $data);
            //订单退款记录日志
            BalanceLogModel::add(SceneEnum::REFUND, [
                'user_id'         => (int)$orderInfo['user_id'],
                'money'           => $cash,
                'correlation_id'  => $orderInfo['order_parent_id'],
                'bd_type'         => $orderInfo['bd_type'],
                'deduction_value' => $deductionValue,
            ], ['order_no' => $orderInfo['order_no']]);
            return true;
        } else {
            throwError($res['message']);
        }
        return false;
    }

    /*public static function bdPay($pay_data,$api_url){
        if($pay_data['userId']){
            $user = (new \yii\db\Query())
                ->select('bd_uid,openId,uniacid')
                ->from('{{%ybo2ov2_member}}')
                ->where('id=:id', [':id' => $pay_data['userId']])->one();
        }
        if(!isset($user['bd_uid']) || empty($user['bd_uid'])){
            return false;
        }
        $token_array = self::createToken($user['bd_uid']);
        $pay_data['timestamp'] = time();
        $pay_data['platform'] = 'shopping';
        $pay_data['recommendUserId'] = $user['bd_uid'];
        $pay_data['openId'] = $user['openId'];
        $sign = self::getBangDouApiSign($pay_data);
        $pay_data['sign'] = $sign;
        $headers = [
            'Content-Type: application/json',
            "Authorization: Bearer {$token_array['token']}"
        ];
        $result = httpRequest($api_url, json_encode($pay_data), $headers);
        $res = json_decode($result, true);
        return $res;
    }*/

    /**
     * 调用心链接口创建订单
     * @param $pay_data
     * @return bool
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function OrderXinLianPayment($pay_data)
    {
        $xinlian = new OpenApiService();
        /*$response = $xinlian->queryBalance();
        $result   = $response->getBody()->getContents();//获取账户余额*/
        //if ($pay_data['user_id'] == '1' || $pay_data['user_id'] == '16') {//临时测试充值不到账*/
        if (strpos($_SERVER['HTTP_HOST'],'dev') !== false) {//临时测试充值不到账*/
            $result['data']      = array('order_no' => 'OD48589909447328672', 'merchant_no' => $pay_data['order_no']);
            $result['timestamp'] = time();
            $result['code']      = 200;
            $result['message']   = '请求成功';
        } else {
            $format   = array('account' => $pay_data['recharge_account']);
            $response = $xinlian->createOrder($pay_data['order_no'], $pay_data['goods_no'], $format);//创建订单
            $result   = $response->getBody()->getContents();
            $result   = json_decode($result, true);
        }
        $log_file = runtime_root_path() . 'api/log/xinlian/give_order_' . date('y-m-d') . '.log';
        file_put_contents($log_file, print_r($result, true) . "\n", FILE_APPEND);
        if ($result['code'] == 200) {
            OrderCallbackLogModel::add('xinlian', [
                'user_id'          => (int)$pay_data['user_id'],
                'recharge_account' => $pay_data['recharge_account'],
                'order_no'         => $pay_data['order_no'],
                'order_id'         => $pay_data['order_id'],
                'goods_no'         => $pay_data['goods_no'],
                'merchant_no'      => $result['data']['order_no'],//第三方心链订单编号
            ]);
            return true;
        }
        return false;
    }

    /**
     * 余额充值送三券
     * @param $order
     * @return bool
     */
    public static function rechargeGiveBd($order)
    {
        $info                              = OrderPlanModel::detail(['order_id' => $order['order_id']]);
        $token_array                       = self::createTokenByuserId($order['user_id']);
        $pay_data['timestamp']             = time();
        $pay_data['platform']              = 'shopping';
        $pay_data['rewardBangdouTotal']    = $info['give_bd'];
        $pay_data['rewardCouponTotal']     = $info['give_coupon'];
        $pay_data['rewardCouponGiftTotal'] = $info['give_gift_coupon'];
        $pay_data['orderNo']               = $order['out_trade_no'];
        $pay_data['storeId']               = $info['store_id'];
        $pay_data['organId']               = self::ORGANID;
        $pay_data['remark']               = '邦豆百货余额充值返券';
        $sign                              = self::getBangDouApiSign($pay_data);
        $pay_data['sign']                  = $sign;
        $headers                           = [
            'Content-Type: application/json',
            "Authorization: Bearer {$token_array['token']}"
        ];
        $api_url  = app()->config->get('app.bd_api_url') . '/Order/Order/sendBangdouAndCoupon';
        $result   = helper::httpRequest($api_url, json_encode($pay_data), $headers);
        $res      = json_decode($result, true);
        log_record($res);
        if ($res['state'] == true) {
            $data['give_bd']          = $info['give_bd'];//赠送的邦豆
            $data['give_coupon']      = $info['give_coupon'];//赠送的现金券
            $data['give_gift_coupon'] = $info['give_gift_coupon'];//赠送的礼金券
            $rechargeOrderModel = new RechargeOrderModel();
            $rechargeOrderModel->where('order_id', $order['order_id'])->update($data);
            $bd_type = ['7' => $info['give_bd'], '6' => $info['give_coupon'], '5' => $info['give_gift_coupon']];
            //新增余额变动记录
            foreach ($bd_type as $key => $value) {
                BalanceLogModel::add(SceneEnum::RECHARGE, [
                    'user_id'         => (int)$order['user_id'],
                    'money'           => 0.00,
                    'correlation_id'  => $order['order_id'],
                    'bd_type'         => $key,
                    'deduction_value' => $value,
                ], ['order_no' => '余额充值赠送']);
            }
            return true;
        }
        return false;
    }
}
